<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT 客户端</title>
   <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
            display: flex;
            flex-direction: column; /* 默认垂直方向排列 */
        }

        div.container {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px; /* 为了与日志框分开 */
        }

        div.logs {
            background: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            max-height: 500px;
            overflow-y: auto;
        }

        /* 大屏设备的布局 */
        @media (min-width: 768px) {
            body {
                flex-direction: row; /* 大屏设备时横向排列 */
            }

            div.container {
                flex: 1;
                margin-right: 20px;
                margin-bottom: 0; /* 取消底部边距 */
            }

            div.logs {
                flex: 1;
                margin-left: 20px;
            }
        }

        .form-group {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        label {
            font-weight: bold;
            flex: 1;
            margin-right: 10px;
        }

        input[type="text"], input[type="number"], select {
            flex: 2;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            background-color: #28a745;
            color: white;
            cursor: pointer;
            margin-top: 10px;
        }

        button:hover {
            background-color: #218838;
        }

        .message-box {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .log-message {
            margin: 5px 0;
            font-size: 12px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="form-group">
        <div >
            <label>主机地址：</label>
            <input id="hostInput" type="text" placeholder="输入Broker主机名，如broker.emqx.io" value="broker.emqx.io">
        </div>
        <div >
            <label>端口：</label>
            <input id="portInput" type="text" placeholder="输入Broker端口，如8083" value="8083">
        </div>
    </div>


    <div class="form-group">
        <label>协议类型：(选了也没用)</label>
        <select id="protocolInput">
            <option value="ws">ws://（WebSocket）</option>
            <option value="mqtt">mqtt://（普通MQTT）</option>
        </select>
    </div>

    <div class="form-group">
        <label>自定义Client ID：</label>
        <input id="clientIdInput" type="text" placeholder="输入Client ID" value="mqtt_client_webtest_1">
    </div>

    <div class="form-group">
        <label>目标主题：</label>
        <input id="targetTopicInput" type="text" placeholder="LEDTEST" value="LEDTEST">
        <label>指定QoS：</label>
        <input id="qosInput" type="number" placeholder="输入Qos值(0, 1, 2)" value="0">
    </div>

    <div class="form-group">
        <button onclick="connect()">连接</button>
        <button onclick="subscribe()">订阅</button>
        <button onclick="disconnect()">断开连接</button>
        <button onclick="clearMessage()">清空</button>
    </div>

    <div class="form-group">
        <div class="message-box">
            <label>快捷消息1：</label>
            <input id="quickMessage1" type="text" placeholder="快捷消息1" value="Hello">
            <button onclick="sendQuickMessage('quickMessage1')">发送</button>
        </div>
        <div class="message-box">
            <label>快捷消息2：</label>
            <input id="quickMessage2" type="text" placeholder="快捷消息2" value="world">
            <button onclick="sendQuickMessage('quickMessage2')">发送</button>
        </div>
    </div>

    <div class="form-group">

        <div class="message-box">
            <label>快捷消息3：</label>
            <input id="quickMessage3" type="text" placeholder="快捷消息3" value="1">
            <button onclick="sendQuickMessage('quickMessage3')">发送</button>
        </div>
        <div class="message-box">
            <label>快捷消息4：</label>
            <input id="quickMessage4" type="text" placeholder="快捷消息4" value="0">
            <button onclick="sendQuickMessage('quickMessage4')">发送</button>
        </div>
    </div>
    <div class="form-group">
        <div class="message-box">
            <label>快捷消息5：</label>
            <input id="quickMessage5" type="text" placeholder="快捷消息5" value="Hi">
            <button onclick="sendQuickMessage('quickMessage5')">发送</button>
        </div>
        <div class="message-box">
            <label>快捷消息6：</label>
            <input id="quickMessage6" type="text" placeholder="快捷消息6" value="there">
            <button onclick="sendQuickMessage('quickMessage6')">发送</button>
        </div>
    </div>

    <div class="form-group">
        <div class="message-box">
            <label>快捷消息7：</label>
            <input id="quickMessage7" type="text" placeholder="快捷消息7" value="How are you?">
            <button onclick="sendQuickMessage('quickMessage7')">发送</button>
        </div>
        <div class="message-box">
            <label>快捷消息8：</label>
            <input id="quickMessage8" type="text" placeholder="快捷消息8" value="I'm fine">
            <button onclick="sendQuickMessage('quickMessage8')">发送</button>
        </div>
    </div>

    <div class="form-group">
        <label>长消息：</label>
        <input id="longMessageInput" type="text" placeholder="长消息" value="Thank you">
        <button onclick="sendQuickMessage('longMessageInput')">发送</button>

    </div>


    <div id="messageDiv"></div>
</div>

<div class="logs">
    <h4>日志窗口</h4>

    <div class="form-group">
        <label>过滤消息主题：</label>
        <select id="filterTopicInput">
            <option value="所有">所有</option>
            <!--            <option value="LEDTEST">LEDTEST</option>-->
            <!--            <option value="MQTT">MQTT</option>-->
            <!--            <option value="mqtt">mqtt</option>-->
            <!-- 这里将添加已订阅的主题 -->
        </select>
    </div>
    <div id="logDiv"></div>
</div>

<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
    let client;

    function connect() {
        const host = document.getElementById("hostInput").value;
        const port = document.getElementById("portInput").value;
        const clientId = document.getElementById("clientIdInput").value;
        const protocol = document.getElementById("protocolInput").value;

        let url;
        if (protocol === 'mqtt') {
            url = `mqtt://${host}:${port}/mqtt`;
        } else {
            url = `ws://${host}:${port}/mqtt`;
        }

        // 检查是否已经存在一个client实例，如果是，则先断开连接
        if (client && client.connected) {
            client.end();
        }

        // 创建新的client实例
        client = mqtt.connect(url, {clientId: clientId});

        client.on('connect', function () {
            showLog('已连接到MQTT Broker');
        });

        client.on('message', function (topic, message) {
            const filterTopic = document.getElementById("filterTopicInput").value;
            if (filterTopic === "所有" || filterTopic === topic) {
                showLog(`时间[${new Date().toLocaleString()}] 收到消息：主题[${topic}] 内容[${message.toString()}] `);
            }
        });
    }

    function subscribe() {
        const targetTopic = document.getElementById("targetTopicInput").value;
        client.subscribe(targetTopic, function (err) {
            if (!err) {
                showLog(`时间[${new Date().toLocaleString()}] 成功订阅主题：${targetTopic} `);
                addSubscribedTopicToFilter(targetTopic); // 添加主题到过滤下拉框
            }
        });
    }

    function sendQuickMessage(id) {
        const targetTopic = document.getElementById("targetTopicInput").value;
        const qos = parseInt(document.getElementById("qosInput").value) || 0;
        const message = document.getElementById(id).value;
        client.publish(targetTopic, message, {qos: qos});
        showLog(`时间[${new Date().toLocaleString()}] 发送消息到主题[${targetTopic}] 内容[${message}] QoS[${qos}] `);
    }

    function showLog(message) {
        const logDiv = document.getElementById("logDiv");
        const logEle = document.createElement("div");
        logEle.className = 'log-message';
        logEle.innerText = message;
        logDiv.appendChild(logEle);
        logDiv.scrollTop = logDiv.scrollHeight;
    }

    function clearMessage() {
        const messageDiv = document.getElementById("messageDiv");
        messageDiv.innerHTML = "";
        const logDiv = document.getElementById("logDiv");
        logDiv.innerHTML = "";
    }

    function addSubscribedTopicToFilter(topic) {
        const filterTopicInput = document.getElementById("filterTopicInput");
        const option = document.createElement("option");
        option.value = topic;
        option.text = topic;
        filterTopicInput.appendChild(option);
    }

    function disconnect() {
        if (client) {
            client.end();
            showLog('已断开与MQTT Broker的连接');
        }
    }
</script>
</body>
</html>
